package com.ivyft.ftpserver.hdfs;

import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.User;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * <pre>
 *
 * Created by IntelliJ IDEA.
 * User: zhenqin
 * Date: 15/10/29
 * Time: 12:00
 * To change this template use File | Settings | File Templates.
 *
 * </pre>
 *
 * @author zhenqin
 */
public class HdfsFileSystemFactory implements FileSystemFactory {
    private final Logger LOG = LoggerFactory.getLogger(HdfsFileSystemFactory.class);
    private boolean createHome = true;
    private boolean caseInsensitive;


    private final FileSystem fileSystem;


    public HdfsFileSystemFactory() {
        this(new Configuration());
    }


    public HdfsFileSystemFactory(Configuration conf) {
        try {
            this.fileSystem = FileSystem.get(conf);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }



    public HdfsFileSystemFactory(FileSystem fileSystem) {
        this.fileSystem = fileSystem;
    }


    @Override
    public FileSystemView createFileSystemView(User user) throws FtpException {
        synchronized (user) {
            if (this.createHome) {
                String homeDirStr = user.getHomeDirectory();
                Path homeDir = new Path(homeDirStr);
                try {
                    if (fileSystem.isFile(homeDir)) {
                        this.LOG.warn("Not a directory :: " + homeDirStr);
                        throw new FtpException("Not a directory :: " + homeDirStr);
                    }
                    if ((!fileSystem.exists(homeDir)) && (!fileSystem.mkdirs(homeDir))) {
                        this.LOG.warn("Cannot create user home :: " + homeDirStr);
                        throw new FtpException("Cannot create user home :: " + homeDirStr);
                    }
                } catch (IOException e) {
                    throw new FtpException("Cannot create user home :: " + homeDirStr);
                }

            }
        }

        FileSystemView fsView = new HdfsFileSystemView(user, fileSystem, this.caseInsensitive);
        return fsView;
    }


    public boolean isCreateHome() {
        return createHome;
    }

    public void setCreateHome(boolean createHome) {
        this.createHome = createHome;
    }

    public boolean isCaseInsensitive() {
        return caseInsensitive;
    }

    public void setCaseInsensitive(boolean caseInsensitive) {
        this.caseInsensitive = caseInsensitive;
    }
}
